/**
 * Created by Jiangxtx on 2017/1/4.
 * This module aims to wrap fetch request and some common methods about fetch-request.
 * As you need ajax request, USE fetch here, thus can improve stability in the long run.
 *      --jiangxtx 2017-1-4
 */

import Promise from 'promise-polyfill'
import 'whatwg-fetch'

if (!window.Promise) {
    window.Promise = Promise;
}
const fetch = fetch;

/**
 * 检测 fetch 请求是否正确响应
 *      fetch(url)
 .then(fetchStatusCheck).then(res => res.json() ).then.....
 * @param response
 * @returns {*}
 */
const fetchStatusCheck = (response) => {
    if ( (response.status >= 200 && response.status < 300) || response.ok) {
        return response;
    } else {
        var error = new Error(response.statusText)
        error.response = response
        throw error;
    }
}

/**
 * 获取请求数据的 json 数据，返回 Promise 对象
 * @param response
 */
const parseJSON = (response) => response.json()

const FETCH_POST_WithData = (postArrData) => ({
    method:'post',
    credentials: 'include',
    headers:{
        'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8',
        'Accept': 'application/json, text/javascript,*/*;q=0.01'
    },
    body: arrToFetchData(postArrData)
});

/**
 * post 发送数组类型参数，主要用于适配 fetch 模式下的前后数据传输格式
 * @param senddataArr 数组类型参数名称 待传输参数，数组类型
 *      形如：     senddataArr: [
 *                          { name: 'score', data: [85, 68, 91] },
 *                          { name: 'subject', data: ['chinese', 'maths', 'English'] },
 *                        ],
 *      输出结果：  score[]=85&score[]=68&score[]=91&subject[]=chinese&subject[]=maths&subject[]=English
 *      用途：     用于 POST 传参
 * @return 序列化后的string
 */
export function arrToFetchData(senddataArr) {

    const _arrToFetchPostJson = (sendArrData, arrName) => {
        let strArr = []
        sendArrData.map( item => strArr.push(`${arrName}[]=${item}`) );
        return strArr.join('&');
    }
    const fetchDataArr = senddataArr.map(item => _arrToFetchPostJson(item.data, item.name));
    return fetchDataArr.join('&');
}

export { fetch, fetchStatusCheck, parseJSON, arrToFetchData }